import asyncio
import os

import oss2


def make_oss_bucket(
    access_key_id: str | None = None,
    access_key_secret: str | None = None,
    oss_endpoint: str | None = None,
    oss_bucket: str | None = None,
):
    access_key_id = access_key_id or os.environ["ACCESS_KEY_ID"]
    access_key_secret = access_key_secret or os.environ["ACCESS_KEY_SECRET"]
    oss_endpoint = oss_endpoint or os.environ["OSS_ENDPOINT"]
    oss_bucket = oss_bucket or os.environ["OSS_BUCKET"]
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, oss_endpoint, oss_bucket)
    return bucket


bucket = make_oss_bucket()


async def upload_file_to_oss(bin_data: bytes, file_name: str):
    """上传文件到 OSS"""
    await asyncio.to_thread(bucket.put_object, file_name, bin_data)


async def make_upload_link(
    file_name: str,
    content_type: str | None = None,
    timeout: int = 60 * 60 * 24,
):
    """生成上传链接"""
    url = await asyncio.to_thread(
        bucket.sign_url,
        "PUT",
        file_name,
        timeout,
        {
            "Content-Type": content_type,
        },
    )
    return url


async def get_download_link(file_name: str, timeout: int = 60 * 60 * 24):
    """生成下载链接"""
    url = await asyncio.to_thread(bucket.sign_url, "GET", file_name, timeout)
    return url
